package tabletask

import (
	"io/ioutil"
	"os"
	"time"

	"cvevulner/cve-timed-task/db_models"
	"cvevulner/cve-timed-task/downloadfiletask"
	"cvevulner/models"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/pkg/errors"
)

// AddErrorDetails Conditions for filtering incorrect data
func AddErrorDetails() {
	ormModel := orm.NewOrm()
	filePath, err := downloadfiletask.DownloadSpecErrorExcels()
	if err != nil {
		logs.Error("downloadfiletask.DownloadSpecErrorExcels error:", err)
		return
	}

	files, err := ioutil.ReadDir(filePath)
	if err != nil {
		logs.Error(" ioutil.ReadDir error: ", err, filePath)
		return
	}

	for _, file := range files {
		fileName := file.Name()
		if file.IsDir() {
			logs.Warn(filePath+fileName, "is Dir, remove")
			_ = os.RemoveAll(filePath + fileName)
			continue
		}
		excel, err := excelize.OpenFile(filePath + fileName)
		if err != nil {
			logs.Error("excelize.OpenReader:", err)
			continue
		}

		rows, err := excel.GetRows("Sheet1")
		if err != nil {
			logs.Error("excel.GetRows Sheet1 error", err)
			continue
		}
		var cveNum string
		var cveDesc string
		var cveOwner string
		var packName string
		now := time.Now().Format("2006-01-02 15:04:05")
		for _, row := range rows[1:] {
			if len(row) < 2 {
				continue
			}
			cveNum = row[1]
			if len(row) > 2 {
				cveOwner = row[2]
				if len(row) > 3 {
					packName = row[3]
					if len(row) > 4 {
						cveDesc = row[4]
					} else {
						cveDesc = ""
					}
				} else {
					packName = ""
				}
			} else {
				cveOwner = ""
			}
			tranErr := ormModel.Begin()
			if tranErr != nil {
				logs.Error(" Open transaction error:", tranErr.Error())
				continue
			}
			specError, err := db_models.GetCveSpecError(cveNum, ormModel)
			if err != nil {
				if errors.Is(orm.ErrNoRows, err) {
					_, err = db_models.InsertCveSpecError(&models.SpecError{
						CveNum:      cveNum,
						Description: cveDesc,
						Owner:       cveOwner,
						Status:      1,
						PackName:    packName,
						CreateTime:  now,
					}, ormModel)
					if err != nil {
						logs.Error("db_models.InsertCveSpecError:", err)
						tranErr = ormModel.Rollback()
						if tranErr != nil {
							logs.Error(" Rollback transaction error:", tranErr.Error())
						}
						continue
					}
				} else {
					logs.Error("db_models.GetCveSpecError:", err)
					tranErr = ormModel.Rollback()
					if tranErr != nil {
						logs.Error(" Rollback transaction error:", tranErr.Error())
					}
					continue
				}
			} else {
				if specError.Description != cveDesc || specError.Owner != cveOwner || specError.PackName != packName || specError.Status != 1 {
					err := db_models.UpdateCveSpecError(models.SpecError{
						CveNum:      specError.CveNum,
						Description: cveDesc,
						Owner:       cveOwner,
						PackName:    packName,
						Status:      1,
						UpdateTime:  now,
					}, ormModel)
					if err != nil {
						logs.Error("db_models.UpdateCveSpecError:", err)
						tranErr = ormModel.Rollback()
						if tranErr != nil {
							logs.Error(" Rollback transaction error:", tranErr.Error())
						}
						continue
					}
				}
			}
			tranErr = ormModel.Commit()
			if tranErr != nil {
				logs.Error(" Commit transaction error:", tranErr.Error())
				continue
			}
		}
		_ = os.Remove(filePath + fileName)
	}
}
